const mongoose = require('mongoose');
const ProductSchema = new mongoose.Schema({
  name: { type: String, default: '' },
  cover: { type: String, default: '' },
  price: { type: Number, default: 1 }
}, { timestamps: true })

/** 定义了名为id的虚拟属性 */
ProductSchema.virtual('id').get(function () {
  return this._id.toHexString()
})

/** 实体转为json时转换虚拟属性 */
ProductSchema.set('toJSON', {
  virtuals: true
})

ProductSchema.set('toObject', {
  virtuals: true
})

const Product = mongoose.model('Product', ProductSchema)
/** 计数为0是插入数据 */
Product.countDocuments().then(count => {
  if (count == 0) {
    Product.create({
      name: '小米手机',
      cover: 'https://img.yzcdn.cn/vant/ipad.jpeg',
      price: 1
    });
    Product.create({
      name: '华为手机',
      cover: 'https://img.yzcdn.cn/vant/ipad.jpeg',
      price: 2
    });
    Product.create({
      name: '苹果手机',
      cover: 'https://img.yzcdn.cn/vant/ipad.jpeg',
      price: 3
    });
  }
})

module.exports = Product;